/*
 * @Description:
 * @Author: zheng yiliang
 * @Date: 2021-03-28 16:12:02
 * @LastEditTime: 2021-04-12 22:04:39
 * @LastEditors: zheng yiliang
 */
var express = require('express');
var router = express.Router();
const { SuccessModel, ErrorModel } = require('../util')
const loginCheck = require('../middleware/loginCheck')
const { Users, Roles, Menu } = require('../model')
// const { Role } = require('../model/roles')
const { mapMenus } = require('../util/fn')


// 获取用户角色列表
router.get('/allRoles', loginCheck, async (req, res) => {
  const { roleId, roleName, roleKey, dateRange } = req.query
  let params = {}
  if (roleId) params._id = roleId
  if (roleName) params.role_name = { $regex: eval(`/${roleName}/ig`) }
  if (roleKey) params.role_key = { $regex: eval(`/${roleKey}/ig`) }
  if (dateRange) params.create_time = {
    "$gte": new Date(`${dateRange[0]} 00:00:00`),
    "$lte": new Date(`${dateRange[1]} 23:59:59`)
  }
  const roles = await Roles.find(params, { create_time: 1, role_name: 1, role_desc: 1, menus: 1, role_key: 1 })
  const roleMap = await Promise.all(roles.map(async item => {
    const menus = await Menu.find({ menu_id: { $in: item.menus } }, { _id: false }) //根据 menu_id 数组查对应菜单
    const menuFomate = mapMenus(menus)
    return {
      roleName: item.role_name,
      roleDesc: item.role_desc,
      roleKey: item.role_key,
      roleId: item._id,
      children: menuFomate,
      createTime: item.create_time
    }
  }))

  return res.json(new SuccessModel(roleMap, '角色列表获取成功'))
})

router.get('/userInfo', loginCheck, async (req, res) => {
  // console.log(req)
  const token = req.user_id

  const userInfo = await Users.findInfo(token)

  res.json(new SuccessModel(userInfo, '用户信息获取成功'))
})

// 编辑角色
router.put('/update', loginCheck, async (req, res) => {
  const { roleDesc, roleId, roleName, roleKey } = req.body
  const result = await Roles.findByIdAndUpdate(roleId, {
    role_desc: roleDesc,
    role_name: roleName,
    role_key: roleKey
  })
  return res.json(new SuccessModel('角色修改成功'))
})

// 删除角色
router.delete('/delete', loginCheck, async (req, res) => {
  const { roleId } = req.body
  const result = await Roles.findByIdAndDelete(roleId)
  return res.json(new SuccessModel('角色删除成功'))
})

// 添加角色
router.post('/add', loginCheck, async (req, res) => {
  const { roleDesc, roleKey, roleName, rights } = req.body
  const role = new Roles({
    role_desc: roleDesc,
    role_key: roleKey,
    role_name: roleName,
    menus: rights
  });
  /*实例.save((err,docs)=>{回调函数}) 来将数据保存到数据库*/
  role.save((err, docs) => {
    if (err) {
      const { keyValue } = err
      // console.log(err)
      if (keyValue.role_key) {
        return res.json(new ErrorModel('角色关键字已存在'))
      }
      if (keyValue.role_name) {
        return res.json(new ErrorModel('角色名称已存在'))
      }
      return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
    }
    return res.json(new SuccessModel('角色添加成功'))
  });
})

// 权限列表
router.get('/rightTree', loginCheck, async (req, res) => {
  const menus = await Menu.find()
  // console.log(menus)
  const result = mapMenus(menus)
  return res.json(new SuccessModel(result, '获取权限列表成功'))
})

// 权限设置
router.put('/rights/set', loginCheck, async (req, res) => {
  const { rights, roleId } = req.body
  // console.log(rights, roleId)
  const result = await Roles.findByIdAndUpdate(roleId, {
    menus: rights
  })
  return res.json(new SuccessModel('权限设置成功'))
})

// 取消权限
router.delete('/rights/cancel', loginCheck, async (req, res) => {
  const { rightId, roleId } = req.body
  // console.log(rightId, roleId)
  const result = await Roles.findByIdAndUpdate(roleId, { $pull: { menus: { $in: rightId } } })
  const role = await Roles.findById(result._id)
  const menus = await Menu.find({ menu_id: { $in: role.menus } }, { _id: false }) //根据 menu_id 数组查对应菜单
  const menuFomate = mapMenus(menus)
  // console.log(menuFomate)
  return res.json(new SuccessModel(menuFomate, '权限取消成功'))
})

module.exports = router;